<template>
  <div class="app-container">
    <el-card>
      <!-- 筛选区域 -->
      <el-form :model="filterForm" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="3">
            <el-form-item label="药剂名称">
              <el-input v-model="filterForm.reagentName" placeholder="输入药剂名称" clearable>
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="药剂规格">
              <el-input v-model="filterForm.specification" placeholder="输入规格型号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="库存状态">
              <el-select v-model="filterForm.stockStatus" placeholder="选择库存状态" clearable style="width: 100%">
                <el-option label="全部" value="" />
                <el-option label="预警" value="0" />
                <el-option label="正常" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="药剂类型">
              <el-select v-model="filterForm.drugType" placeholder="选择库存状态" clearable style="width: 100%">
                <el-option v-for="value in drugTypeListOptions" :key="value.id" :label="value.name" :value="value.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="时间范围">
              <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="5" class="text-left">
            <el-button type="primary" :icon="Search" @click="handleQuery">
              查询
            </el-button>
            <el-button :icon="Refresh" @click="handleReset">
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="mt-2">
      <!-- 操作按钮 -->
      <div class="mb-2">
        <el-button type="primary" :icon="Plus" @click="handleAdd">
          新增
        </el-button>
        <el-button :icon="Box" @click="handleStockIn">
          入库
        </el-button>
        <el-button :icon="Truck" @click="handleStockOut">
          出库
        </el-button>
        <el-button :icon="Edit" @click="handleUsageRegister">
          使用登记
        </el-button>

        <el-button type="success" :icon="Download"
          @click="handleExport(`/operation/web/operationPharmaceuticalList/export`)">
          导出药剂清单列表
        </el-button>
      </div>

      <!-- 药剂表格 -->
      <el-table :data="medicineList" border style="width: 100%" v-loading="loading" class="mt-2"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="reagentName" label="药品名称" align="center" />
        <el-table-column prop="reagentName" label="药剂类型" align="center">
          <template #default="{ row }">
            <el-tag>{{ getName(drugTypeListOptions, row.drugType, 'id', 'name') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格型号" align="center" />
        <el-table-column prop="manufacturer" label="生产厂家" align="center" />
        <el-table-column prop="batchNumber" label="批次号" align="center" />
        <el-table-column prop="currentStock" label="当前库存" align="center">
          <template #default="{ row }">
            <el-tag :type="getStockTagType(row)">
              {{ row.currentStock }} {{ row.unit }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="计量单位" align="center" />
        <el-table-column prop="inventoryWarningValue" label="库存预警值" align="center" />
        <el-table-column label="操作" align="center" fixed="right" width="220">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleDetail(row)">
              详情
            </el-button>
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleDelete(row)" style="color: #f56c6c">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 新增/编辑药剂对话框 -->
    <el-dialog :title="formType === 'add' ? '新增药剂' : '编辑药剂'" v-model="medicineFormVisible" width="600px"
      :close-on-click-modal="false">
      <el-form ref="medicineFormRef" :model="medicineForm" :rules="formRules" label-width="120px" label-position="left">
        <el-form-item label="药剂名称" prop="reagentName">
          <el-input v-model="medicineForm.reagentName" placeholder="输入药剂名称" clearable />
        </el-form-item>

        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="medicineForm.specification" placeholder="输入规格型号" clearable />
        </el-form-item>

        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="medicineForm.manufacturer" placeholder="输入生产厂家" clearable />
        </el-form-item>

        <el-form-item label="计量单位" prop="unit">
          <el-select v-model="medicineForm.unit" placeholder="请选择计量单位" style="width: 100%">
            <el-option label="千克" value="kg" />
            <el-option label="升" value="L" />
            <el-option label="克" value="g" />
            <el-option label="毫升" value="ml" />
            <el-option label="吨" value="t" />
          </el-select>
        </el-form-item>

        <el-form-item label="库存预警值" prop="inventoryWarningValue">
          <el-input-number v-model="medicineForm.inventoryWarningValue" :min="1" :max="9999" controls-position="right"
            style="width: 100%" />
        </el-form-item>

        <el-form-item label="药剂图片">
          <!-- <el-upload
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleImageUploadSuccess">
            <el-button type="primary">上传图片</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png格式，大小不超过2MB
              </div>
            </template>
          </el-upload> -->
          <UploadFile v-model:fileIds="medicineForm.image" :type="'image'" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="medicineFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 入库对话框 -->
    <el-dialog title="药剂入库" v-model="warehouseVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="stockInFormRef" :model="stockInForm" :rules="warehouseFormRules" label-width="120px">
        <el-form-item label="药剂名称" prop="drugId">
          <el-select v-model="stockInForm.drugId" placeholder="选择药剂" filterable style="width: 100%">
            <el-option v-for="item in medicineList" :key="item.id" :label="item.reagentName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="入库数量" prop="quantity">
          <el-input-number v-model="stockInForm.quantity" :min="1" :max="9999" controls-position="right"
            style="width: 100%" />
        </el-form-item>

        <el-form-item label="批次号" prop="batchNumber">
          <el-input v-model="stockInForm.batchNumber" placeholder="输入批次号" clearable />
        </el-form-item>

        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker v-model="stockInForm.productionDate" type="date" placeholder="选择生产日期"
            value-format="YYYY-MM-DD" style="width: 100%" />
        </el-form-item>

        <el-form-item label="保质期(月)" prop="expirationDate">
          <el-input-number v-model="stockInForm.expirationDate" :min="1" :max="120" controls-position="right"
            style="width: 100%" />
        </el-form-item>

        <el-form-item label="供应商" prop="supplierName">
          <el-input v-model="stockInForm.supplierName" placeholder="输入供应商" clearable />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="stockInForm.remark" type="textarea" :rows="3" placeholder="输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="warehouseVisible = false">取消</el-button>

          <el-button type="primary" @click="submitStockIn">
            确认入库
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 出库对话框 -->
    <el-dialog title="药剂出库" v-model="outVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="stockOutFormRef" :model="stockOutForm" :rules="stockOutRules" label-width="120px">
        <el-form-item label="药剂名称" prop="drugId">
          <el-select v-model="stockOutForm.drugId" placeholder="选择药剂" filterable style="width: 100%">
            <el-option v-for="item in medicineList" :key="item.id" :label="item.reagentName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="出库数量" prop="quantity">
          <el-input-number v-model="stockOutForm.quantity" :min="1" :max="9999" controls-position="right"
            style="width: 100%" />
        </el-form-item>

        <el-form-item label="出库用途" prop="purpose">
          <el-input v-model="stockOutForm.purpose" type="textarea" :rows="3" placeholder="输入出库用途" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="outVisible = false">取消</el-button>
          <!-- <el-button type="success" icon="Download" @click="handleExport">
            导出出入库记录
          </el-button> -->
          <el-button type="primary" @click="submitStockOut">
            确认出库
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 使用登记对话框 -->
    <el-dialog title="药剂使用登记" v-model="useVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="useFormRef" :model="useForm" :rules="useFormRules" label-width="120px">
        <el-form-item label="药剂名称" prop="drugId">
          <el-select v-model="useForm.drugId" placeholder="选择药剂" filterable style="width: 100%">
            <el-option v-for="item in medicineList" :key="item.id" :label="item.reagentName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="使用数量" prop="quantity">
          <el-input-number v-model="useForm.quantity" :min="1" :max="9999" controls-position="right"
            style="width: 100%" />
        </el-form-item>

        <el-form-item label="使用说明" prop="purpose">
          <el-input v-model="useForm.purpose" type="textarea" :rows="3" placeholder="输入使用说明" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="useForm.remark" type="textarea" :rows="3" placeholder="输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="useVisible = false">取消</el-button>
          <el-button type="success" :icon="Download" @click="handleExport">
            导出使用记录
          </el-button>
          <el-button type="primary" @click="submitUseRegister">
            确认登记
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 药剂详情对话框 -->
    <el-dialog title="药剂详情" v-model="detailVisible" width="900px" top="5vh" :close-on-click-modal="false">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions border :column="2">
            <el-descriptions-item :rowspan="1" label="Photo">
              <el-image style="width: 100px; height: 100px" :src="currentDetail.image" />
            </el-descriptions-item>
            <el-descriptions-item label="药剂名称">{{ currentDetail.reagentName }}</el-descriptions-item>
            <el-descriptions-item label="规格型号">{{ currentDetail.specification }}</el-descriptions-item>
            <el-descriptions-item label="生产厂家">{{ currentDetail.manufacturer }}</el-descriptions-item>
            <el-descriptions-item label="批次号">{{ currentDetail.batchNumber }}</el-descriptions-item>
            <el-descriptions-item label="当前库存">
              <el-tag :type="getStockTagType(currentDetail)">
                {{ currentDetail.currentStock }} {{ currentDetail.unit }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="库存预警值">{{ currentDetail.inventoryWarningValue }} {{ currentDetail.unit
            }}</el-descriptions-item>
            <el-descriptions-item label="计量单位">{{ currentDetail.unit }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentDetail.createTime }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="出入库记录" name="stock">
          <el-table :data="stockRecords" border style="width: 100%">
            <el-table-column prop="operationTime" label="操作时间" width="180" />
            <el-table-column prop="operationType" label="操作类型" width="100">
              <template #default="{ row }">
                <el-tag :type="row.operationType === 0 ? 'success' : 'danger'">
                  {{ row.operationType === 0 ? '入库' : '出库' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="120" />
            <el-table-column prop="operator" label="操作人" width="120" />
            <el-table-column prop="batchNumber" label="批次号" width="150" />
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="使用记录" name="usage">

          <el-table :data="usageRecords" border style="width: 100%">
            <el-table-column prop="usageDate" label="使用日期" width="180" />
            <el-table-column prop="quantity" label="使用量" width="120" />
            <el-table-column prop="usedBy" label="使用人" width="120" />
            <el-table-column prop="purpose" label="使用说明" />
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" icon="Download"
            @click="handleExport(`/operation/web/operationPharmaceuticalList/inOutRecordExcel/${currentDetail.id}`)"
            v-if="activeTab == 'stock'">
            导出出入库记录
          </el-button>
          <el-button type="success" icon="Download"
            @click="handleExport(`/operation/web/operationPharmaceuticalList/useExcel/${currentDetail.id}`)"
            v-if="activeTab == 'usage'">
            导出使用记录
          </el-button>
          <el-button @click="detailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import UploadFile from '@/components/UploadFile'
import {
  listPharmaceuticalList,
  getPharmaceuticalDetail,
  getInOutRecord,
  getUseRecord,
  addPharmaceuticalList,
  updatePharmaceuticalList,
  deletePharmaceuticalList,
  stockIn,
  stockOut,
  useRegister,
  getDrugTypeList
} from '@/api/prod_operate/prod_run/drug_manage/inventory'
const { proxy } = getCurrentInstance();

// 数据状态
const loading = ref(false)
const medicineFormVisible = ref(false)
const warehouseVisible = ref(false)
const outVisible = ref(false)
const useVisible = ref(false)
const detailVisible = ref(false)
const activeTab = ref('basic')
const formType = ref('add') // 'add' or 'edit'
const selectedRows = ref([])

const drugTypeListOptions = ref([])

// 筛选表单
const filterForm = reactive({
  reagentName: '',
  specification: '',
  manufacturer: '',
  stockStatus: '',
  dateRange: []
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const medicineForm = reactive({
  id: null,
  reagentName: '',
  specification: '',
  manufacturer: '',
  unit: 'kg',
  inventoryWarningValue: 100,
  image: ''
})

// 入库表单
const stockInForm = reactive({
  drugId: null,
  quantity: 1,
  batchNumber: '',
  productionDate: '',
  expirationDate: '',
  supplierName: '',
  remark: ''
})

// 出库表单
const stockOutForm = reactive({
  drugId: null,
  quantity: 1,
  purpose: ''
})

// 使用登记表单
const useForm = reactive({
  drugId: null,
  quantity: 1,
  purpose: '',
  remark: ''
})

// 详情数据
const currentDetail = ref({})
const stockRecords = ref([])
const usageRecords = ref([])

// 药剂列表数据
const medicineList = ref([])

// 表单验证规则
const formRules = reactive({
  reagentName: [
    { required: true, message: '请输入药剂名称', trigger: 'blur' }
  ],
  specification: [
    { required: true, message: '请输入规格型号', trigger: 'blur' }
  ],
  manufacturer: [
    { required: true, message: '请输入生产厂家', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请选择计量单位', trigger: 'change' }
  ],
  inventoryWarningValue: [
    { required: true, message: '请输入库存预警值', trigger: 'blur' }
  ]
})

// 入库表单验证规则
const warehouseFormRules = reactive({
  drugId: [
    { required: true, message: '请选择药剂', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入入库数量', trigger: 'blur' }
  ],
  batchNumber: [
    { required: true, message: '请输入批次号', trigger: 'blur' }
  ],
  productionDate: [
    { required: true, message: '请选择生产日期', trigger: 'change' }
  ]
})

// 出库表单验证规则
const stockOutRules = reactive({
  drugId: [
    { required: true, message: '请选择药剂', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入出库数量', trigger: 'blur' }
  ],
  purpose: [
    { required: true, message: '请输入出库用途', trigger: 'blur' }
  ]
})

// 使用登记表单验证规则
const useFormRules = reactive({
  drugId: [
    { required: true, message: '请选择药剂', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入使用数量', trigger: 'blur' }
  ],
  purpose: [
    { required: true, message: '请输入使用说明', trigger: 'blur' }
  ]
})

// 获取库存标签类型
const getStockTagType = (medicine) => {
  if (!medicine.inventoryWarningValue || !medicine.currentStock) return ''

  if (medicine.currentStock < medicine.inventoryWarningValue * 0.3) {
    return 'danger'
  } else if (medicine.currentStock < medicine.inventoryWarningValue) {
    return 'warning'
  }
  return 'success'
}

// 获取药剂列表
const fetchMedicineList = async () => {
  try {
    loading.value = true
    const params = {
      reagentName: filterForm.reagentName,
      specification: filterForm.specification,
      manufacturer: filterForm.manufacturer,
      stockStatus: filterForm.stockStatus,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    if (filterForm.dateRange?.length === 2) {
      params.startTime = filterForm.dateRange[0]
      params.endTime = filterForm.dateRange[1]
    }

    const res = await listPharmaceuticalList(params)
    medicineList.value = res.rows || []
    pagination.total = res.total || 0

    const drugTypeList = await getDrugTypeList();
    drugTypeListOptions.value = drugTypeList.data;
  } catch (error) {
    console.error('获取药剂列表失败:', error)
    ElMessage.error('获取药剂列表失败')
  } finally {
    loading.value = false
  }
}

// 获取药剂详情
const fetchMedicineDetail = async (id) => {
  try {
    const res = await getPharmaceuticalDetail(id)
    currentDetail.value = res.data || {}

    // 获取出入库记录
    const inOutRes = await getInOutRecord(id)
    stockRecords.value = inOutRes.data || []

    // 获取使用记录
    const useRes = await getUseRecord(id)
    usageRecords.value = useRes.data || []

  } catch (error) {
    console.error('获取药剂详情失败:', error)
    ElMessage.error('获取药剂详情失败')
  }
}

// 查询处理
const handleQuery = () => {
  pagination.currentPage = 1
  fetchMedicineList()
}

// 重置查询
const handleReset = () => {
  Object.assign(filterForm, {
    reagentName: '',
    specification: '',
    manufacturer: '',
    stockStatus: '',
    dateRange: []
  })
  handleQuery()
}

// 新增药剂
const handleAdd = () => {
  formType.value = 'add'
  Object.assign(medicineForm, {
    id: null,
    reagentName: '',
    specification: '',
    manufacturer: '',
    unit: 'kg',
    inventoryWarningValue: 100,
    image: ''
  })
  medicineFormVisible.value = true
}

// 编辑药剂
const handleEdit = (row) => {

  console.log(row);

  formType.value = 'edit'
  Object.assign(medicineForm, {
    id: row.id,
    reagentName: row.reagentName,
    specification: row.specification,
    manufacturer: row.manufacturer,
    unit: row.unit,
    inventoryWarningValue: row.inventoryWarningValue,
    image: row.image
  })
  medicineFormVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    if (formType.value === 'add') {
      await addPharmaceuticalList(medicineForm)
      ElMessage.success('新增药剂成功')
    } else {
      await updatePharmaceuticalList(medicineForm)
      ElMessage.success('修改药剂成功')
    }
    medicineFormVisible.value = false
    fetchMedicineList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 入库操作
const handleStockIn = () => {
  warehouseVisible.value = true
  Object.assign(stockInForm, {
    drugId: null,
    quantity: 1,
    batchNumber: '',
    productionDate: '',
    expirationDate: '',
    supplierName: '',
    remark: ''
  })
}

// 提交入库
const submitStockIn = async () => {
  try {
    await stockIn(stockInForm)
    ElMessage.success('入库成功')
    warehouseVisible.value = false
    fetchMedicineList()
  } catch (error) {
    console.error('入库失败:', error)
    ElMessage.error('入库失败')
  }
}

// 出库操作
const handleStockOut = (row) => {
  outVisible.value = true
  Object.assign(stockOutForm, {
    drugId: row ? row.id : null,
    quantity: 1,
    purpose: ''
  })
}

// 提交出库
const submitStockOut = async () => {
  try {
    await stockOut(stockOutForm)
    ElMessage.success('出库成功')
    outVisible.value = false
    fetchMedicineList()
  } catch (error) {
    console.error('出库失败:', error)
    ElMessage.error('出库失败')
  }
}

// 使用登记
const handleUsageRegister = (row) => {
  useVisible.value = true
  Object.assign(useForm, {
    drugId: row ? row.id : null,
    quantity: 1,
    purpose: '',
    remark: ''
  })
}

// 提交使用登记
const submitUseRegister = async () => {
  try {
    await useRegister(useForm)
    ElMessage.success('使用登记成功')
    useVisible.value = false
    fetchMedicineList()
  } catch (error) {
    console.error('使用登记失败:', error)
    ElMessage.error('使用登记失败')
  }
}

// 查看详情
const handleDetail = async (row) => {
  await fetchMedicineDetail(row.id)
  detailVisible.value = true
}

// 删除药剂
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除药剂【${row.reagentName}】吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deletePharmaceuticalList(row.id)
      ElMessage.success('删除成功')
      fetchMedicineList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 导出数据
async function handleExport(url) {
  try {
    proxy.download(url, filterForm, `user_${new Date().getTime()}.xlsx`);
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 图片上传成功
const handleImageUploadSuccess = (response) => {
  medicineForm.image = response.data.url
  ElMessage.success('图片上传成功')
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchMedicineList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchMedicineList()
}

// 初始化数据
onMounted(() => {
  fetchMedicineList()
})
</script>

<style scoped>
.text-right {
  text-align: right;
}

.highlight-text {
  color: #409EFF;
  font-weight: bold;
}
</style>